package com.example.elmmerchants.First_Page_Fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.example.elmmerchants.Set_Open_Shop_Page;
import com.example.elmmerchants.Product_Management.Shop_Management_Page;
import com.example.elmmerchants.Shop_Activity.Setting_Shop_Activity_Page;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Shop_Page extends Fragment {

    View root;
    TextView shop_name_text_view, shop_mark, shop_sold_text_view, is_open_shop_text_view;
    RatingBar shop_star_rating;
    LinearLayout set_is_open_shop, shop_management, set_activity_page;
    AlertDialog dialog;

    String email, shop_name, open_hour, close_hour, open_day, close_hour_2, open_hour_2;
    byte[] shop_pic_string = new byte[0];
    int is_open_shop, shop_sold, can_served_start_time, can_served_end_time, is_open_book_order, is_all_day_can_book_order;
    double shop_star;
    boolean is_loading_open_shop_page_data = false, is_loading_shop_management_page = false, is_loading_shop_page_data = false;
    int all = 0, sold = 0, do_not_sold = 0, do_not_buy = 0;

    public Shop_Page(String email) {
        this.email = email;
    }

    private class Open_Shop_Thread extends Thread {
        @Override
        public void run() {
            is_loading_open_shop_page_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        open_hour = set.getString("open_hour");
                        close_hour = set.getString("close_hour");
                        open_day = set.getString("open_day");
                        close_hour_2 = set.getString("close_hour2");
                        open_hour_2 = set.getString("open_hour2");
                        shop_pic_string = set.getBytes("shop_picture");
                    }

                    String sql2 = "SELECT * FROM merchant_book_order_setting WHERE email = ?;";
                    PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                    preparedStatement2.setString(1, email);
                    ResultSet set2 = preparedStatement2.executeQuery();
                    while (set2.next()) {
                        can_served_start_time = set2.getInt("can_served_start_time");
                        can_served_end_time = set2.getInt("can_served_end_time");
                        is_open_book_order = set2.getInt("is_open_book_order");
                        is_all_day_can_book_order = set2.getInt("is_all_day_can_book_order");
                    }
                    is_loading_open_shop_page_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_open_shop_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(root.getContext(), Set_Open_Shop_Page.class);
                    intent.putExtra("email", email);
                    intent.putExtra("is_open_shop", is_open_shop);
                    intent.putExtra("open_hour", open_hour);
                    intent.putExtra("close_hour", close_hour);
                    intent.putExtra("can_served_start_time", can_served_start_time);
                    intent.putExtra("can_served_end_time", can_served_end_time);
                    intent.putExtra("is_open_book_order", is_open_book_order);
                    intent.putExtra("is_all_day_can_book_order", is_all_day_can_book_order);
                    intent.putExtra("open_day", open_day);
                    intent.putExtra("close_hour_2", close_hour_2);
                    intent.putExtra("open_hour_2", open_hour_2);
                    intent.putExtra("shop_name", shop_name);
                    startActivityForResult(intent, 1);
                }
            });
        }
    }

    private class Shop_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_shop_page_data = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        shop_name = set.getString("shop_name");
                        is_open_shop = set.getInt("is_open");
                        shop_sold = set.getInt("shop_sold");
                        shop_star = set.getDouble("shop_star");
                        is_loading_shop_page_data = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_shop_page_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (isVisible()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        shop_name_text_view.setText(shop_name);
                        shop_mark.setText(String.valueOf(shop_star));
                        shop_star_rating.setRating((float) shop_star);
                        shop_sold_text_view.setText(String.valueOf(shop_sold));
                        if (is_open_shop == 1) {
                            is_open_shop_text_view.setText("营业中");
                        }
                        else {
                            is_open_shop_text_view.setText("休息中");
                        }

                        onStop();
                    }
                });
            }
            else {
                onStop();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_shop__page, container, false);

        shop_name_text_view = root.findViewById(R.id.shop_name);
        shop_mark = root.findViewById(R.id.shop_mark);
        shop_star_rating = root.findViewById(R.id.shop_star_rating);
        shop_sold_text_view = root.findViewById(R.id.shop_sold_text_view);
        is_open_shop_text_view = root.findViewById(R.id.is_open_shop_text_view);
        set_is_open_shop = root.findViewById(R.id.set_is_open_shop);
        shop_management = root.findViewById(R.id.shop_management);
        set_activity_page = root.findViewById(R.id.set_activity_page);

        Shop_Data_Thread shopDataThread = new Shop_Data_Thread();
        shopDataThread.start();

        set_is_open_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Open_Shop_Thread openShopThread = new Open_Shop_Thread();
                openShopThread.start();
            }
        });

        shop_management.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(root.getContext(), Shop_Management_Page.class);
                intent.putExtra("email", email);
                startActivity(intent);
            }
        });

        set_activity_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(root.getContext(), Setting_Shop_Activity_Page.class);
                intent.putExtra("email", email);
                intent.putExtra("shop_name", shop_name);
                startActivity(intent);
            }
        });

        return root;
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
        LayoutInflater inflater1 = LayoutInflater.from(root.getContext());
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1: {
                if (data != null) {
                    if (data.getStringExtra("is_open_shop").equals("休息中")) {
                        is_open_shop = 0;
                    }
                    else {
                        is_open_shop = 1;
                    }
                    is_open_shop_text_view.setText(data.getStringExtra("is_open_shop"));
                }
            }
        }
    }
}